/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */

import { AdaptorErrorMessage } from '@ohos/hvigor-logger';

import { TraceManager } from './trace-manager.js';
import { HvigorTraceData } from './type.js';

class HvigorTrace {
  public static readonly TRACE_KEY = 'HVIGOR';
  private data: HvigorTraceData;

  constructor() {
    this.data = {
      IS_INCREMENTAL: true,
      IS_DAEMON: true,
      IS_PARALLEL: true,
      IS_HVIGORFILE_TYPE_CHECK: false,
      TASK_TIME: {},
      APIS: new Set<string>(),
    };
  }

  /**
   * 传输数据给打点管理中心并且在落盘后清理数据
   */
  public transmitDataToManager(): void {
    TraceManager.trace(HvigorTrace.TRACE_KEY, this.data, () => {
      delete this.data.BUILD_ID;
      delete this.data.ERROR_MESSAGE;
      this.data.TASK_TIME = {};
      this.data.APIS.clear();
    });
  }

  public traceTotalTime(totalTime: number): void {
    this.data.TOTAL_TIME = totalTime;
  }

  /**
   * 记录并行、增量、daemon、类型检查的配置的值
   */
  public traceBaseConfig(
    IS_INCREMENTAL: boolean,
    IS_DAEMON: boolean,
    IS_PARALLEL: boolean,
    IS_HVIGORFILE_TYPE_CHECK: boolean
  ): void {
    this.data.IS_INCREMENTAL = IS_INCREMENTAL;
    this.data.IS_DAEMON = IS_DAEMON;
    this.data.IS_PARALLEL = IS_PARALLEL;
    this.data.IS_HVIGORFILE_TYPE_CHECK = IS_HVIGORFILE_TYPE_CHECK;
  }

  public traceBuildId(buildId: string): void {
    this.data.BUILD_ID = buildId;
  }

  public traceTaskTime(taskName: string, moduleName: string, time: number): void {
    let moduleNameAlias;
    if (moduleName === '') {
      moduleNameAlias = 'APP';
    } else {
      moduleNameAlias = TraceManager.transformKey(TraceManager.anonymize(moduleName));
    }
    const singleTaskName = taskName.substring(taskName.indexOf('@') + 1);
    const taskTime = this.data.TASK_TIME?.[moduleNameAlias] ?? {};
    taskTime[singleTaskName] = time;
    if (this.data.TASK_TIME) {
      this.data.TASK_TIME[moduleNameAlias] = taskTime;
    }
  }

  public traceErrorMessage(adaptorErrorMessage: AdaptorErrorMessage): void {
    this.data.ERROR_MESSAGE = this.data.ERROR_MESSAGE ?? [];
    this.data.ERROR_MESSAGE.push({
      CODE: adaptorErrorMessage.code,
      MESSAGE: adaptorErrorMessage.originMessage,
      SOLUTIONS: adaptorErrorMessage.originSolutions,
      MORE_INFO: adaptorErrorMessage.moreInfo,
      TIMESTAMP: adaptorErrorMessage.timestamp?.getTime().toString(),
      COMPONENTS: adaptorErrorMessage.components,
      CHECK_MESSAGE: adaptorErrorMessage.checkMessage,
    });
  }

  public insertUsedApi(apiName: string): void {
    if (!this.data.APIS.has(apiName)) {
      this.data.APIS.add(apiName);
    }
  }

  public traceConfigProperties(configProperties: { [key: string]: any }) {

    // MongoDB的key值不允许包含"."，此处将"."替换为"_"
    configProperties = Object.entries(configProperties).reduce((acc, [key, val]) => {
      const newKey = TraceManager.transformKey(key);
      acc[newKey] = val;
      return acc;
    }, {} as { [key: string]: any });

    this.data.CONFIG_PROPERTIES = configProperties;
  }
}

export const hvigorTrace = new HvigorTrace();